#include "curveplotmanager.h"
#include <QDebug>

CurvePlotManager::CurvePlotManager(QWidget *parent)
    : QWidget(parent)
{
    /** 初始化网格布局 */
    m_DyLayout = new DynamicLayout(this);
    DynamicLayout *gLayout = m_DyLayout;
    gLayout->setContentsMargins(0,0,0,0);
    this->setLayout(gLayout);

    /** 创建图表 */
    QStringList curverNames = {"curver_1", "curver_2", "curver_3", "curver_4"};


    connect(this, &CurvePlotManager::seletWidget, m_DyLayout, &DynamicLayout::do_selectedWidget);
}

CurvePlotManager::~CurvePlotManager()
{
    // 释放资源

    // 布局类
    if(m_DyLayout) {
        m_DyLayout->deleteLater();
    }

    // 管理的图表类
    for(QWidget *removeWidget : m_curverPlots) {
        if(removeWidget) {
            removeWidget->deleteLater();
        }
    }

    // 定时器类
    if(m_plotTimer) {
        if(m_plotTimer->isActive()) {
            m_plotTimer->stop();
            m_plotTimer->deleteLater();
        }
    }
}

CurvePlot *CurvePlotManager::addCurvePlot(QString newCurvePlot)
{
    qDebug() << "窗口数量:" << m_DyLayout->count();
    qDebug() << "m_curverPlots:" << m_curverPlots;
    if(m_curverPlots.size() >= MAX_CHARTS)
    {
        qDebug() << "窗口数量到达最大，添加失败";
        return nullptr;
    }

    if(newCurvePlot.isEmpty()) {
        qDebug() << "添加的图表名称不能为空";
        return nullptr;
    }

    // 检查是否存在
    if(!m_curverPlots.isEmpty()) {
        if(m_curverPlots.contains(newCurvePlot)) {
            qDebug() << "添加的窗口: " << newCurvePlot << " 已存在，不能同名";
            return nullptr;
        }
    }

    // 配置CurvePlot
    CurvePlot *plot = new CurvePlot(this);
    plot->customPlot()->installEventFilter(this);
//    plot->installEventFilter(this); // 安装事件过滤器
    plot->setName(newCurvePlot);// 设置图表名称

    // 如果只有一张就选中图表
    if(m_curverPlots.isEmpty()) {
        m_currSeleted = plot;
        do_setCurrentSeletState(true);
    }

    m_curverPlots.insert(newCurvePlot, plot);// 添加Map
    m_DyLayout->addManagedWidget(plot); // 添加到布局


    return plot;
}

void CurvePlotManager::removeCurvePlot(QString delCurvePlot)
{
    if(delCurvePlot.isEmpty()) {
        qDebug() << "添加的图表名称不能为空";
        return;
    }
    // 检查是否为空
    if(!m_curverPlots.isEmpty()){
        if(!m_curverPlots.contains(delCurvePlot)) {
            qDebug() << "删除的窗口: " << delCurvePlot << " 不存在";
            return;
        }
    }

    // 获取要删除的CurvePlot
    CurvePlot * delPlot = m_curverPlots.value(delCurvePlot);

    if(!delPlot) {
        qDebug() << "removeCurvePlot<错误>：空指针";
        return;
    }

    // 删除的是选中的
    if(m_currSeleted == delPlot) {
        // 清除选中
        do_setCurrentSeletState(false);

        m_currSeleted = Q_NULLPTR;  // 悬空

        // 如果还有图表，就选中最后一个
        if(!m_curverPlots.isEmpty()) {
            m_currSeleted = m_curverPlots.last();
            do_setCurrentSeletState(true);
        }
    }
    m_DyLayout->removeManagedWidget(delPlot);   // 从布局中移除
    m_curverPlots.remove(delCurvePlot); // 从Map中删除

    delPlot->deleteLater(); // 安全释放

    qDebug() << "m_curverPlots:" << m_curverPlots;
//    if(m_curverPlots.isEmpty()) {
//        this->deleteLater();
//    }
}

void CurvePlotManager::addData(const QString &curvePlotName, const QString &graphName,
                               const double &x, const double &y)
{
    // 获取图表类
    CurvePlot *curvePlot = m_curverPlots.value(curvePlotName);
    if(curvePlot) {
        qDebug() << "addData<错误>：没有找到图表";
        return;
    }

    // 获取Graph
//    QCustomPlot *customplot = curvePlot->customPlot();
    QCPGraph *graph = curvePlot->Curvers().value(graphName);
    if(graph) {
        graph->addData(x, y);   // 添加数据
    }

    // 刷新
    curvePlot->replotQueue();
}

// 全部刷新
void CurvePlotManager::replot()
{
    for(CurvePlot *curvePlot : m_curverPlots) {
        curvePlot->setRunStatus(true);
        // 刷新
        curvePlot->replotQueue();
    }
}
// 获取所有图表信息，曲线信息
QVariantMap CurvePlotManager::getCurvePlotInfo()
{
    QVariantMap curvePlotInfo;

    for(const CurvePlot *curvePlot : m_curverPlots){
        // 获取图表名称和曲线信息Map
        curvePlotInfo.insert(curvePlot->name(), curvePlot->getCurveInfo());
    }
    return curvePlotInfo;
}

void CurvePlotManager::setLayouModel(CurvePlotManager::LayoutType type)
{
    switch (type) {
    case One:{
        // 单独显示
        m_DyLayout->setOneLayoutFlag(true);
        break;
    }
    case Rese:{
        // 显示多个
        m_DyLayout->setOneLayoutFlag(false);
        break;
    }
    default:{

        break;
    }
    }
}

bool CurvePlotManager::eventFilter(QObject *object, QEvent *event)
{
    // 防御性检查：空指针和无效事件类型
    if (!object || !event) {
        return QObject::eventFilter(object, event); // 确保事件链完整
    }



    // 鼠标双击事件
    if(event->type() == QEvent::MouseButtonDblClick) {
        qDebug().nospace() << "\n\n鼠标双击事件对象: " << object;


        // 安全类型转换（两步验证）
        QCustomPlot* clickedWidget = qobject_cast<QCustomPlot*>(object);
        CurvePlot* clickedParent = clickedWidget ? qobject_cast<CurvePlot*>(clickedWidget->parent()) : nullptr;

        if (!clickedWidget || !clickedParent) {
            qWarning() << "类型转换失败，忽略事件";
            return QObject::eventFilter(object, event);
        }
//        qDebug() << "object->parent():" << object;
//        qDebug() << "object->parent().parent():" << object->parent();
//        qDebug() << "m_currSeleted:" << m_currSeleted;
//        qDebug() << "clickedWidget:" << clickedWidget;
//        qDebug() << "clickedParent:" << clickedParent;


        emit seletWidget(m_currSeleted);
        LayoutType model = m_DyLayout->getOneLayoutFlag() ? LayoutType::Rese : LayoutType::One;

        setLayouModel(model);

        return QObject::eventFilter(object, event);
    }


    // 鼠标点击事件
    if(event->type() == QEvent::MouseButtonPress) {
        qDebug().nospace() << "\n\n鼠标点击事件对象: " << object;

        // 安全类型转换（两步验证）
        QCustomPlot* clickedWidget = qobject_cast<QCustomPlot*>(object);
        CurvePlot* clickedParent = clickedWidget ? qobject_cast<CurvePlot*>(clickedWidget->parent()) : nullptr;

        if (!clickedWidget || !clickedParent) {
            qWarning() << "类型转换失败，忽略事件";
            return QObject::eventFilter(object, event);
        }
//        qDebug() << "object->parent():" << object;
//        qDebug() << "object->parent().parent():" << object->parent();
//        qDebug() << "m_currSeleted:" << m_currSeleted;
//        qDebug() << "clickedWidget:" << clickedWidget;
//        qDebug() << "clickedParent:" << clickedParent;


        // 重复点击优化
        if (clickedParent == m_currSeleted) {
            qDebug() << "重复点击当前选中控件，忽略";
            return QObject::eventFilter(object, event);
//            return true; // 阻止事件进一步传播
        }

        // 清除旧状态前检查有效性
        if (m_currSeleted && m_currSeleted->customPlot()) {
            do_setCurrentSeletState(false);
        }

        // 更新选中状态
        m_currSeleted = clickedParent;
        do_setCurrentSeletState(true);

        qDebug() << "当前选中控件更新为: " << m_currSeleted;
        return QObject::eventFilter(object, event);
//        return true; // 事件已处理
    }



    // 不处理事件时直接返回false
//    return false;
    return QObject::eventFilter(object, event);
}

void CurvePlotManager::do_setCurrentSeletState(bool b)
{
//    QWidget *widget = m_currSeleted;
    if(b) {
        m_currSeleted->setStyleSheet("QWidget { border: 2px solid red; }");
//        m_currSeleted->setProperty("selected", true);
    } else {
        m_currSeleted->setStyleSheet("");
//        m_currSeleted->setProperty("selected", false);
    }
}

QString CurvePlotManager::name() const
{
    return m_name;
}

void CurvePlotManager::setName(const QString &name)
{
    m_name = name;
}

QMap<QString, CurvePlot *> CurvePlotManager::curverPlots() const
{
    return m_curverPlots;
}

void CurvePlotManager::setCurverPlots(const QMap<QString, CurvePlot *> &curverPlots)
{
    m_curverPlots = curverPlots;
}

CurvePlot *CurvePlotManager::currSeleted() const
{
    return m_currSeleted;
}

void CurvePlotManager::setCurrSeleted(CurvePlot *currSeleted)
{
    m_currSeleted = currSeleted;
}
